from django import forms
from django.core.exceptions import ValidationError
from web.form.bootstrap import BootStrapForm
from web import models


# from utils.tencent.cos import *
from web.models import FileRepository


class FolderModelForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.FileRepository
        fields = ['name']

    def __init__(self, request, parent_object, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent_object = parent_object

    def clean_name(self):
        name = self.cleaned_data['name']

        # 数据库判断 当前目录 下 此 文件夹是否存在     根据  url 是否有   ?fielder     （文件夹url） localhost:8000/web/file/?fielder=(num)
        queryset = models.FileRepository.objects.filter(file_type=2, name=name, project=self.request.tracer.project)
        if self.parent_object:
            exists = queryset.filter(parent=self.parent_object).exists()
        else:
            exists = queryset.filter(parent__isnull=True).exists()
        if exists:
            raise ValidationError('文件夹已存在')
        return name

class FileModeForm(forms.ModelForm):
    etag = forms.CharField(label='ETag')

    class Meta:
        model = FileRepository  # 修正这里
        exclude = ['project', 'file_type', 'update_user', 'update_datetime']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_file_path(self):
        # 假设 self.cleaned_data['file_path'] 应该包含文件的路径
        # 这里需要确保 file_path 是有效的，并且可以被格式化为 URL
        file_path = self.cleaned_data['file_path']
        # 如果 file_path 是一个简单的路径，您可能需要将其转换为完整的 URL
        # 例如："https://yourdomain.com{}".format(file_path)
        return "https://{}".format(file_path)  # 确保这里的 {} 被替换为有效的路径


    # etag = forms.CharField(label='ETag')
    #
    # class Meta:
    #     models = models.FileRepository
    #     exclude = ['project','file_type','update_user','update_datetime']
    #
    # def __init__(self,request,*args,**kwargs):
    #     super().__init__(*args,**kwargs)
    #     self.request = request
    #
    # def clean_file_path(self):
    #     return "https://{}".format(self.cleaned_data['file_path'])